import { App, ref, Ref } from "vue";
import type { ModuleInterface, ModuleConfig, SendCmd } from "./types";
import TestForm from "./components/index.vue";
// 2. 修复：导入泛型 Response 类型（确保是泛型版本）
import type { Response } from "./types";
import { SEND_TEST_CMD_KEY, GET_TEST_DATA_KEY } from "./types"; // 导入字符串Key

const config: ModuleConfig = {
  id: "TestForm",
  name: "测试模块",
  version: "1.0.0",
  description: "任务测试"
};

export class TestModule<
  EventData extends object = object, // 约束为对象，解决 Object.assign 问题
  Payload = any,
  Return = Response<any> // 泛型 Response，解决问题2&5
> implements ModuleInterface<EventData, Payload, Return> {

  config = config;
  public eventData: Ref<EventData>; // 直接暴露响应式对象
  private sendCmd: SendCmd<Payload, Return>;

  constructor(initialData: EventData, sendCmd: SendCmd<Payload, Return>) {
    this.eventData = ref(initialData) as Ref<EventData>;
    this.sendCmd = sendCmd;
  }

  sendCommand(cmd: string, payload?: Payload): Return | Promise<Return> {
    console.log("插件发送指令：", cmd, payload);
    return this.sendCmd(this.config.id, cmd, payload);
  }

  install(app: App): void {
    // app.component("TestForm", TestForm);

    app.provide(GET_TEST_DATA_KEY, this.eventData);

    app.provide(SEND_TEST_CMD_KEY, (cmd: string, payload?: Payload): Return | Promise<Return> => {
      console.log("插件内部转发指令：", cmd, payload);
      return this.sendCommand(cmd, payload);
    });
  }

  getEventData(): EventData {
    return this.eventData as EventData;
  }

  updateEventData(data: Partial<EventData>): void {
    Object.assign(this.eventData as Object, data);
  }

  async startup(): Promise<void> {
    console.log("测试模块初始化完成");
  }
}

export const createTestModule = <
  EventData extends object = object,
  Payload = any,
  Return = Response<any>
>(
  initialData: EventData,
  sendCmd: SendCmd<Payload, Return>
): ModuleInterface<EventData, Payload, Return> => {
  return new TestModule<EventData, Payload, Return>(initialData, sendCmd);
};

export default createTestModule;